package com.example.javafx.bilibilidownload.util;

import com.fasterxml.jackson.databind.ser.AnyGetterWriter;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author zengbang
 * @create 2024-08-09 10:54
 **/
public class CacheUtil {

    public static Map<String, Object> cacheMap = new ConcurrentHashMap();

    public static void initFxmlInfo(String simpleName, String fxmlPath) {

        if(cacheMap.containsKey(simpleName + "c")){
            // 说明已经初始化过了，就不再初始化了
        }
        else{
            // 初始化
            FXMLLoader fxmlLoader = new FXMLLoader(CacheUtil.class.getResource(fxmlPath));
            try {
                cacheMap.putIfAbsent(simpleName + "p", fxmlLoader.load());
                cacheMap.putIfAbsent(simpleName + "c", fxmlLoader.getController());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static <T> T getFxmlController(Class<T> clazz, String fxmlPath) {
        initFxmlInfo(clazz.getSimpleName(), fxmlPath);
        return (T) cacheMap.get(clazz.getSimpleName() + "c");
    }

    public static <T> Parent getFxmlPane(Class<T> clazz, String fxmlPath) {
        initFxmlInfo(clazz.getSimpleName(), fxmlPath);
        return (Parent) cacheMap.get(clazz.getSimpleName() + "p");
    }
}
